<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :visible="visible"
    :mask-closable="false"
    :destroy-on-close="true"
    @close="onClose"
  >
    <TaskTitle title-name="价格变更-发起" />
    <div class="g-drawer-list-container">
      <TitleSecondary title="基本信息" />
      <FormPriceBasicInfo
        ref="form"
        :is-empty-array.sync="isEmptyArray"
        :form-info="formInfo"
        :res-form="resForm"
        :plan-type="planType"
        :has-default="hasDefault"
        :curr-status="currStatus"
        @clear-list="clearList"
        @get-form="getform"
        @res-data="resData"
      />
      <TitleSecondary title="价格变更明细" />
      <TablePriceChangeDetailed
        ref="table"
        :key-array="keyArray"
        :form-data="formData"
        :plan-type="planType"
        :parent-id="form.salesOrganization"
        :plan-id="planId"
        :forms="forms"
        :time-range="timeRange"
        :visible.sync="visibled"
        :res-form="resForm"
        :form-info="formInfo"
        :is-empty-array.sync="isEmptyArray"
        :res-source.sync="resSource"
        @validate="validate"
      />
      <ProgressLog
        v-if="currStatus !== '0'"
        :list="logs"
        style="margin-top: 20px"
      />
      <BottomLine />
    </div>
    <ButtonGroup
      class="g-drawer-footer"
      :options="filterButtons"
      @click="handleButtonClick"
    />
  </p-drawer>
</template>

<script>
import monent from 'moment';
import FormPriceBasicInfo from '@/components/task/FormPriceBasicInfo.vue';
import { postStartPriceChange } from '@/api/price.js';
import TablePriceChangeDetailed from '@/components/task/TablePriceChangeDetailed.vue';
import { postForecast } from '@/api/public';
import ProgressLog from '@/components/task/ProgressLog.vue';

import DrawerMixin from './mixin'; //注释

export default {
  components: {
    FormPriceBasicInfo,
    TablePriceChangeDetailed,
    ProgressLog,
  },
  mixins: [DrawerMixin],
  props: {
    keyArray: {
      type: Array,
      default: () => [],
    },
    formData: {
      type: Array,
      default: () => [],
    },
    dateArr: {
      type: Array,
      default: () => [],
    },
    hasDefault: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      resForm: false,
      forms: {},
      planIdNew: undefined,
      saleList: [],
      visibled: false,
      isEmptyArray: false,
      resSource: false,
    };
  },

  computed: {
    footerButtons() {
      return [
        {
          key: 'submit',
          type: 'primary',
          label: '提交',
          auth: true,
        },
        {
          key: 'save',
          label: '保存',
          auth: true,
        },
        {
          key: 'close',
          label: '返回',
        },
      ];
    },
  },
  watch: {},

  methods: {
    resData() {
      this.resSource = true;
    },
    async validate() {
      const result = await this.$refs.form.validate();
      // console.log(result);
      if (result) {
        this.visibled = true;
      }
    },
    clearList(val) {
      this.resForm = val;
    },
    onClose() {
      this.isEmptyArray = false;
      this.$emit('update:visible', false);
      this.$emit('change-currstatus', '0');
      this.$emit('fresh');
    },
    getform(val) {
      this.forms = val;
    },

    copy() {
      const data = this.$refs.table.getDataSource().map((item) => {
        const newPrice = Object.keys(item).filter((key) =>
          key.startsWith('newPriceMonth')
        );
        const obj = newPrice.reduce((pre, cur) => {
          const month = cur.split('PriceMonth')[1];
          let itemCur = +item[cur];
          if (month) {
            pre[month] = itemCur?.toFixed(2);
          }
          return pre;
        }, {});
        return {
          ...item,
          newPrice: JSON.stringify(obj),
        };
      });
      return data;
    },
    aRoute(object) {
      let isEmpty = false;
      Object.keys(object).forEach((item) => {
        // console.log(object[item]);
        if (object[item] === '') {
          isEmpty = true;
          return;
        }
      });
      if (isEmpty) {
        return true;
      } else {
        return false;
      }
    },
    async submitData(operating) {
      console.log('selectKeys: ', this.$refs.table.keys);
      const copy = this.copy();
      const result = await postForecast({
        bizModule: 'PC',
        currStatus: operating,
      });
      const processId = result?.data.data;
      const list = this.saleList;
      return await postStartPriceChange({
        id: this.priceId,
        serialNumber: this.$refs.form.form.serialNumber,
        salesOrganization: this.$refs.form.form.salesOrganization,
        salesGroup: this.$refs.form.form.salesGroup,
        priceChangeDescribe: this.$refs.form.form.priceChangeDescribe,
        startTime: monent(this.$refs.form.form.startTime).format('YYYY-MM-01'),

        endTime: monent(this.$refs.form.form.endTime).format('YYYY-MM-01'),

        // startTime:
        //   this.$refs.table.dateArr[0] === undefined
        //     ? monent(this.$refs.form.form.startTime).format('YYYY-MM-01')
        //     : this.$refs.table.dateArr[0] + '-01',
        // endTime:
        //   this.$refs.table.dateArr[this.$refs.table.dateArr.length - 1] ===
        //   undefined
        //     ? monent(this.$refs.form.form.endTime).format('YYYY-MM-01')
        //     : this.$refs.table.dateArr[this.$refs.table.dateArr.length - 1] +
        //       '-01',
        processId,
        priceChangeDetails: copy,
        salesGroupName:
          this.$refs.form.orgGroup[this.$refs.form.form.salesGroup],
      });
    },
    async submitCallback() {
      const newPriceArray = [];
      const newPriceArray2 = [];
      let bol = false;
      const copy = this.copy();
      const valid = await this.$refs.form.validate();
      if (!valid) return new Promise(() => {});
      let numData = this.$refs['table'].getSourceVal;
      let dateArr = this.$refs['table'].dateArr;
      const copeSource = this.$refs['table'].copeSource;

      if (numData.length === 0) {
        this.$message.error('请选择需要价格变更明细数据');
        return;
      }
      numData.forEach((item) => {
        dateArr.forEach((el) => {
          // console.log(item[`newPriceMonth${el}`], '````');
          if (
            item[`newPriceMonth${el}`] === undefined ||
            item[`newPriceMonth${el}`] === null ||
            item[`newPriceMonth${el}`] === ''
          ) {
            bol = true;
            return;
          }
        });
      });
      if (bol) {
        this.$message.error('请输入表格中最新的价格');
        return;
      }
      if (copy.length !== 0 && copeSource.length !== 0) {
        copy.forEach((item) => {
          newPriceArray2.push(item.newPrice);
        });
        copeSource.forEach((item) => {
          newPriceArray.push(item.newPrice);
        });
        // console.log(
        //   'newPriceArray: ',
        //   // JSON.stringify(newPriceArray),
        //   // JSON.stringify(newPriceArray2),
        //   newPriceArray,
        //   newPriceArray2
        // );
        // const a1 = newPriceArray.toString().replace(/\s/g, '');
        // console.log('a1: ', a1);
        // const a2 = newPriceArray2.toString().replace(/\s/g, '');
        // console.log('a2: ', a2);
        // console.log('a2=====: ', a2 === a1);
        // debugger;
        if (newPriceArray[0] !== null && newPriceArray2[0] !== null) {
          if (
            newPriceArray.toString().replace(/\s/g, '') ===
            newPriceArray2.toString().replace(/\s/g, '')
          ) {
            this.$message.error('选择的变更的价格未改变');
            return;
          }
        }
      }
      const result = await this.submitData('2');
      if (result.data.code === 0) {
        this.$message.success('提交成功！');
      }
      this.resForm = true;
      this.closeCallback();
    },
    async saveCallback() {
      const result = await this.submitData('1');
      if (result.data.code === 0) {
        this.$message.success('保存成功！');
      }
      this.resForm = true;
      const serialNumber = result?.data?.data?.serialNumber;
      this.planIdNew = result?.data?.data?.id;
      this.$refs.form.setForm(serialNumber);
      this.closeCallback();
    },
    closeCallback() {
      this.resForm = true;
      this.onClose();
      this.clearList();
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      // console.log('fn: ', fn);
      this[fn] && this[fn]();
    },
  },
};
</script>





